package com.prig.base.classManger.single.controller;

import com.prig.base.DTO.input.PageKeywordSortDto;
import com.prig.base.classManger.single.dto.SingleDto;
import com.prig.base.classManger.single.entity.Single;
import com.prig.base.classManger.single.service.SingleSevice;
import com.prig.base.util.response.Result;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @Author lww
 * @Description //TODO
 * @Date 2020/11/18 16:17
 **/
@RestController
@Slf4j
@RequestMapping(path = "/singles")
public class SingleController {

    private SingleSevice singleSevice;

    @Autowired
    public void setSingleSevice(SingleSevice singleSevice) {
        this.singleSevice = singleSevice;
    }

    @GetMapping
    public Result getSingles(PageKeywordSortDto pageKeywordSortDto){
        Page<Single> list ;
        list = singleSevice.getList(pageKeywordSortDto);
        return new Result<>(list.getContent(),list.getTotalElements());
    }
    @GetMapping("/{id}")
    public Result getSingle(@PathVariable(name="id")long id){
        Single single  = singleSevice.get(id);
        return new Result<>(single);
    }
    @PostMapping
    public Result addSingle(@RequestBody @Valid SingleDto dto){
        Single single = new Single();
        BeanCopier copier = BeanCopier.create(dto.getClass(),single.getClass(),false);
        copier.copy(dto,single,null);
        Single added = singleSevice.add(single);
        return  new Result<>(added);
    }
    @PutMapping("/{id}")
    public Result edit(@RequestBody @Valid SingleDto dto,@PathVariable(name="id")long id){
        Single single = new Single();
        BeanCopier copier = BeanCopier.create(dto.getClass(),single.getClass(),false);
        copier.copy(dto,single,null);
        single.setId(id);
        Single edit = singleSevice.edit(single);
        return  new Result<>(edit);
    }

    @DeleteMapping("/{id}")
    public Result delete(@ApiParam(value = "id",required = true)@PathVariable(name="id") String ids){
        ids = ids.replaceAll("\"","");
        singleSevice.delete(ids);
        return new Result("删除成功!!");
    }
}
